<template>
  <!-- 运行结果页面 -->
  <div>
    <el-row class="ruleResult container">
      <el-col style="margin-right:10px;" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          @search="searchForm.page=1,searchFunc()"
          @clear="(searchForm.ruleCode = ''), (searchForm.ruleName = ''),(searchForm.ruleType = ''),
          (searchForm.driverType = ''),
          (searchForm.sceneCode = '')"
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="queryRunResult">查看结果数据</el-button>
          </template>
          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="87px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="规则编码：">
                <el-input
                  v-model="searchForm.ruleCode"
                  style="width:150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="规则名称：">
                <el-input
                  v-model="searchForm.ruleName"
                  style="width:150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="规则类型">
                <el-select v-model="searchForm.ruleType" style="width:150px">
                  <el-option label="机构层级" value="0"></el-option>
                  <el-option label="账户层级" value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="分摊方法">
                <el-select v-model="searchForm.driverType" style="width:150px">
                  <el-option label="静态比例表" value="S"></el-option>
                  <el-option label="动态比例" value="D"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="所属场景">
                <el-select v-model="searchForm.sceneCode" style="width:150px">
                  <el-option
                    v-for="item in ruleSceneList"
                    :key="item.sceneCode"
                    :value="item.sceneCode"
                    :label="item.sceneName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </template>
          <!-- 显示隐藏区 -->
          <template slot="columnHide">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="item in textData"
                :label="item.label"
                :key="item.prop"
                >{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </upper-template>

        <el-table ref="multipleTable" :data="tableData" style="width: 100%" @row-click="authorizeFor">
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="ruleCode"
            label="规则编码"
             show-overflow-tooltip
            v-if="columnState[0]"
          >
          </el-table-column>
          <el-table-column
            prop="ruleName"
            label="规则名称 "
             show-overflow-tooltip
            v-if="columnState[1]"
          >
          </el-table-column>

          <el-table-column
            prop="sceneName"
            label="所属场景 "
             show-overflow-tooltip
            v-if="columnState[2]"
          >
          </el-table-column>

          <el-table-column
            prop="ruleType"
            label="规则类型 "
             show-overflow-tooltip
            v-if="columnState[3]"
            :formatter="row => (row.ruleType == 0 ? '机构层级' : '账户层级')"
          >
          </el-table-column>
          <el-table-column
            prop="driverType"
            label="分摊方法 "
             show-overflow-tooltip
            v-if="columnState[4]"
            :formatter="
              row => (row.driverType == 'D' ? '动态比例' : '静态比例表')
            "
          >
          </el-table-column>
          <el-table-column prop="descn" label="状态 " v-if="columnState[5]"
          :formatter="row => (row.descn == '1' ? '运行成功' : '运行失败')"
          >
          </el-table-column>
          <el-table-column
            prop="beginTime"
            label="开始时间"
             show-overflow-tooltip
            sortable
            v-if="columnState[6]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.beginTime">
                {{ timeFormat(scope.row.beginTime) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="endTime"
            label="结束时间"
             show-overflow-tooltip
            sortable
            v-if="columnState[7]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.endTime">
                {{ timeFormat(scope.row.endTime) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column label="运行时长"  show-overflow-tooltip sortable v-if="columnState[8]">
            <template slot-scope="scope">
              <div v-if="scope.row.endTime">
                {{ runTimeCaluate(timeFormat(scope.row.beginTime),timeFormat(scope.row.endTime))+"s" }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 查看结果数据弹出框 -->
    <el-dialog
      v-dialogDrag
      title="查看结果数据"
      :visible.sync="runResultDataDi"
      width="70%"
      top="2%"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="结果数据" name="resultDataModel">
          <!-- 操作区域 -->
          <upper-template
            exportIcon
            @exportData="exportData"
            @search="searchRunFunc"
            @clear="(searchRunForm.resultCount = '',
              searchRunForm.beginTimeS = '',
              searchRunForm.beginTimeE = '',
              searchRunForm.endTimeS = '',
              searchRunForm.endTimeE = '',
              searchRunForm.asOfDataTimeS = '',
              searchRunForm.asOfDataTimeE = '')"
          >
            <!-- 操作按钮区 -->
            <template slot="buttonArea">
              <el-button @click="searchEffectFunc">查看影响数据</el-button>
              <el-button @click="backResultData">回滚</el-button>
            </template>
            <!-- 搜索区 -->
            <template slot="searchArea">
              <el-form
                :model="searchRunForm"
                ref="searchRunForm"
                label-width="87px"
                label-position="left"
                size="mini"
              >
                <el-form-item label="开始时间">
                  <el-date-picker
                    v-model="searchRunForm.beginTimeS"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    style="width:180px"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="至">
                  <el-date-picker
                    v-model="searchRunForm.beginTimeE"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    style="width:180px"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间">
                  <el-date-picker
                    v-model="searchRunForm.endTimeS"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    style="width:180px"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="至">
                  <el-date-picker
                    v-model="searchRunForm.endTimeE"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    style="width:180px"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="业务日期">
                  <el-date-picker
                    v-model="searchRunForm.asOfDataTimeS"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    style="width:180px"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="至">
                  <el-date-picker
                    v-model="searchRunForm.asOfDataTimeE"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    style="width:180px"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="影响记录条数">
                  <el-input
                    v-model="searchRunForm.resultCount"
                    style="width:180px"
                  ></el-input>
                </el-form-item>
              </el-form>
            </template>
            <!-- 显示隐藏区 -->
            <template slot="columnHide">
              <el-checkbox-group v-model="checkRunList">
                <el-checkbox
                  v-for="item in runDataConfig"
                  :label="item.label"
                  :key="item.prop"
                  >{{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </upper-template>
          <div style="height:400px">
            <el-table ref="definitionTable" :data="runTableData" style="width: 100%" @row-click="authorizeForTable">
              <el-table-column
                width="55"
                type="selection"
                
              ></el-table-column>
              <el-table-column
                prop="ruleCode"
                label="规则编码"
                show-overflow-tooltip
                v-if="columnRunState[0]"
              >
              </el-table-column>
              <el-table-column
                prop="ruleName"
                label="规则名称 "
                show-overflow-tooltip
                v-if="columnRunState[1]"
              >
              </el-table-column>

              <el-table-column
                prop="driverName"
                label="分摊动因 "
                show-overflow-tooltip
                v-if="columnRunState[2]"
              >
              </el-table-column>
              <el-table-column
                prop="asOfDate"
                label="业务时间"
                show-overflow-tooltip
                sortable
                v-if="columnRunState[3]"
              >
                <template slot-scope="scope">
                  <div v-if="scope.row.beginTime">
                    {{ timeFormatShort(scope.row.beginTime) }}
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="runType"
                label="运行方式 "
                show-overflow-tooltip
                v-if="columnRunState[4]"
                :formatter="
                  row => (row.runType == '1' ? '单独运行' : '场景中运行')
                "
              >
              </el-table-column>
              <el-table-column
                prop="runResult"
                label="运行结果"
                show-overflow-tooltip
                sortable
                v-if="columnRunState[5]"
                :formatter="
                  row => (row.runResult == '1' ? '运行成功' : '运行失败')
                "
              >
              </el-table-column>
              <el-table-column
                prop="resultCount"
                label="影响条数"
                show-overflow-tooltip
                sortable
                v-if="columnRunState[6]"
              >
              </el-table-column>
              <el-table-column
                prop="beginTime"
                label="开始时间"
                sortable
                v-if="columnRunState[7]"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <div v-if="scope.row.beginTime">
                    {{ timeFormat(scope.row.beginTime) }}
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="endTime"
                label="结束时间"
                sortable
                v-if="columnRunState[8]"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <div v-if="scope.row.endTime">
                    {{ timeFormat(scope.row.endTime) }}
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="batchId"
                label="批次号"
                show-overflow-tooltip
                v-if="columnRunState[9]"
              >
              </el-table-column>
            </el-table>
            <pagination
              @size-change="handleRunSizeChange"
              @current-change="handleRunCurrentChange"
              :current-page="searchRunForm.page"
              :page-size="searchRunForm.size"
              @refresh="searchRunFunc"
              :total="runTotal"
            ></pagination>
          </div>
        </el-tab-pane>
        <el-tab-pane label="源数据" name="sourceDataModel">
          <sourceDetail :ruleCode="runRuleCode" :activeName="activeName"/>
        </el-tab-pane>
        <el-tab-pane label="动因数据" name="driverDataModel">
          <driverDetail :ruleCode="runRuleCode" :ruleType="runRuleType" :beginTime="runBeginTime" :activeName="activeName"/>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog
      v-dialogDrag
      title="查看影响数据"
      :visible.sync="effectDataDi"
      width="55%"
      top="3%"
    >
      <effectDataDetail :batchId="batchId" :ruleName="ruleName"/>
    </el-dialog>
    <!-- 回滚数据 -->
    <el-dialog v-dialogDrag
      title="回滚数据"
      :visible.sync="backResultDi"
      width="30%"
      top="3%">
      <el-form
        :model="backDataForm"
        ref="backDataRef"
        label-width="110px"
        label-position="left"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择回滚方式"></el-form-item>
            <el-form-item><el-radio v-model="backDataForm.backType" label="1">回滚本条数据</el-radio></el-form-item>
            <el-form-item><el-radio v-model="backDataForm.backType" label="2">回滚本条及之后所有数据</el-radio></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFormButton">确 定</el-button>
        <el-button @click="cancelTne">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ruleResult } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue"
import onlyOneSearch from "@/components/onlyOneSearch";
import effectDataDetail from "./components/ruleResultDetail";
import driverDetail from "./components/driverDetail";
import sourceDetail from "./components/sourceDetail";
import moment from "moment";
export default {
  data() {
    return {
      //查看结果数据弹窗
      runResultDataDi: false,
      //查看影响数据弹窗
      effectDataDi: false,
      //回滚数据弹出框
      backResultDi: false,
      // 列隐藏依据数据
      textData: [
        { prop: "ruleCode", label: "规则编码", disabled: true },
        { prop: "ruleName", label: "规则名称", disabled: true },
        { prop: "sceneName", label: "所属场景", disabled: true },
        { prop: "ruleType", label: "规则类型", disabled: true },
        { prop: "driverType", label: "分摊方法", disabled: true },
        { prop: "descn", label: "状态", disabled: true },
        { prop: "beginTime", label: "开始时间", disabled: true },
        { prop: "endTime", label: "结束时间", disabled: true },
        { prop: "runTime", label: "运行时长", disabled: true }
      ],
      // 显示的列
      checkList: [],
      //查询时默认条件
      searchForm: {
        page: 1,
        size: 15,
        ruleName: "",
        ruleCode:"",
        ruleType: "",
        driverType: "",
        sceneCode: "",

      },
      //总条数
      total: 0,
      //列表数据
      tableData: [],
      //场景列表
      ruleSceneList: [],
      activeName: "resultDataModel",
      //查看结果数据-结果数据
      //查看结果数据-结果数据列隐藏依据数据
      runDataConfig: [
        { prop: "ruleCode", label: "规则编码", disabled: true, align: "center" },
        { prop: "ruleName", label: "规则名称", disabled: true,align: "center" },
        { prop: "driverName", label: "分摊动因", disabled: true,align: "center" },
        { prop: "asOfDate", label: "业务时间", disabled: true },
        { prop: "runType", label: "运行方式", disabled: true },
        { prop: "runResult", label: "运行结果", disabled: true },
        { prop: "resultCount", label: "影响条数", disabled: true },
        { prop: "beginTime", label: "开始时间", disabled: true },
        { prop: "endTime", label: "结束时间", disabled: true },
        { prop: "batchId", label: "批次号", disabled: true }
      ],
      //查看结果数据-结果数据查询默认条件
      searchRunForm: {
        page: 1,
        size: 15,
        resultCount:""
      },
      //查看结果数据-结果数据显示的列
      checkRunList: [],
      //查看结果数据-结果数据列表数据
      runTableData: [],
      //查看结果数据-结果数据总条数
      runTotal: 0,
      //查看结果数据-结果数据查询条件
      runRuleCode: "",
      runRuleType: "",
      runBeginTime: "",
      //查看影响数据参数
      batchId: "",
      ruleName: "",
      backType: "1",
      backDataForm: []
    };
  },
  components: {
    onlyOneSearch,
    effectDataDetail,
    driverDetail,
    sourceDetail
  },
  created() {
    //初始化显示的列
    this.checkListInit();
    //查看结果数据-结果数据初始化显示的列
    this.checkRunListInit();
    //获取场景列表数据
    this.getRuleSceneList();
  },
  computed: {
    columnState() {
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
    columnRunState() {
      let arr = [],
        arr1 = this.runDataConfig,
        arr2 = this.checkRunList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    }
  },
  mounted() {
    this.searchFunc();
  },
  watch: {},
  methods: {
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    searchFunc() {
      let data = this.searchForm;
      ruleResult.queryRuleResultPage(data).then(res => {
        if (res.code === 200) {
          this.tableData = res.datas.rows;
          this.total = res.datas.total;
        }
      });
    },
    getRuleSceneList() {
      ruleResult.queryRuleSceneList().then(res => {
        if (res.code === 200) {
          this.ruleSceneList = res.datas;
        }
      });
    },
    //计算运行时长
    runTimeCaluate(startTime,endTime) { 
      let sTime = startTime.replace(/-/g,'/')
      let eTime = endTime.replace(/-/g,'/')
      var dateBegin = new Date(sTime);
      var dateEnd = new Date(eTime);
      var dateDiff = (dateEnd.getTime()-dateBegin.getTime())/1000;
      return dateDiff;
    },
    checkRunListInit() {
      this.checkRunList = this.runDataConfig.map(v => {
        return v.label;
      });
    },
    searchRunFunc() {
      let data= {
        ruleCode:this.runRuleCode,
        ruleType:this.runRuleType,
        beginTime: moment(this.runBeginTime).format("YYYY-MM-DD HH:mm:ss"),
        ...this.searchRunForm
      }
      ruleResult.queryRunResultPage(data).then(res => {
        if (res.code === 200) {
          this.runTableData = res.datas.rows;
          this.runTotal = res.datas.total;
        }
      });
    },
    handleClick(tab,event) {
      
    },
    //查看结果数据
    queryRunResult() {
      this.activeName="resultDataModel";
      this.runTableData = undefined;
      this.runTableData = new Array();
      let checked = this.$refs.multipleTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        this.runResultDataDi = true;
        this.configRow = checked[0];
        this.runRuleCode=this.configRow.ruleCode;
        this.runRuleType=this.configRow.ruleType;
        this.runBeginTime=this.configRow.beginTime,
        this.ruleName = this.configRow.ruleName;
        this.searchRunFunc();
      }
    },
    //查看影响数据
    searchEffectFunc() {
      let checked = this.$refs.definitionTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        this.configRow = checked[0];
        let isMaxBatchId = checked[0].isMaxBatchId;
        let resultCount = checked[0].resultCount;
        if(isMaxBatchId == "1"||resultCount>0) {
          this.batchId = this.configRow.batchId;
          this.effectDataDi = true;
        } else {
          return this.$message.warning("不能查看影响数据");
        }
      }
    },
    //回滚弹出框
    backResultData () {
      let checked = this.$refs.definitionTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        this.configRow = checked[0];
        let isMaxBatchId = checked[0].isMaxBatchId;
        let resultCount = checked[0].resultCount;
        if(isMaxBatchId == "1"||resultCount>0) {
          this.batchId = this.configRow.batchId;
          this.backResultDi = true;
        } else {
          return this.$message.warning("不能进行回滚操作");
        }
      }
    },
    //确定回滚
    saveFormButton () {
      let data= {
        batchId:this.batchId,
        ...this.backDataForm
      }
      ruleResult.backResultData(data).then(res => {
        if (res.code === 200) {
          this.backResultDi = false;
          return this.$message.warning(res.message);
        }
      });
    },
    //点击行选中(运行结果首页)
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
          this.$refs.multipleTable.clearSelection()
      }
      this.$refs.multipleTable.toggleRowSelection(row, true)
    },
    //点击行选中(查看结果数据)
    authorizeForTable(row) {
      if (this.$refs.definitionTable) {
          this.$refs.definitionTable.clearSelection()
      }
      this.$refs.definitionTable.toggleRowSelection(row, true)
    },
    //结果数据导出
    exportData() {
      let checked = this.$refs.definitionTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        let isMaxBatchId = checked[0].isMaxBatchId;
        let resultCount = checked[0].resultCount;
        if(isMaxBatchId == "1"||resultCount>0) {
          let data = {
            sqlId:"ruleResult",
            tableName:"ca_rule_review",
            BATCHCODE:checked[0].batchId
          };
          ruleResult.getExportFile(data).then((response) => {
            if(response.code==500&&response.message=="2") {
              this.$message.error('执行SQL查询数据错误');
            } else if (response) {
              var filename = decodeURI(response.headers['content-disposition']).split('=')[1];
              var blob = new Blob([response.data],{
                type:
                "application/vnd.ms-excel;charset=utf-8"
              });
              if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveBlob(blob,filename);
              } else {
                var downloadElement = document.createElement("a");
                var href = window.URL.createObjectURL(blob); //创建下载的链接
                downloadElement.href = href;
                downloadElement.download = filename; //下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
                window.URL.revokeObjectURL(href); //释放掉blob对象
              }
            } else {
              this.$message.error(res.message || '获取失败');
            }
          })
        } else {
          return this.$message.warning("不能进行导出操作");
        }
      }
    },
    //取消
    cancelTne () {
      this.backResultDi = false;
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    timeFormatShort(val) {
      if (val) return moment(val).format("YYYY-MM-DD");
      else return "";
    },
    handleSizeChange(val) {
      this.searchForm.size = val;
      console.log(val, "每页数");
      this.searchFunc();
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(val, "当前页");
      this.searchFunc();
    },
    handleRunSizeChange(val) {
      this.searchRunForm.size = val;
      console.log(val, "每页数");
      this.searchRunFunc();
    },
    handleRunCurrentChange(val) {
      this.searchRunForm.page = val;
      console.log(val, "当前页");
      this.searchRunFunc();
    }
  }
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
</style>